import { useLogin } from '@/hooks/useLogin'
import { getToken, getMember, goback } from '@/utils/common'
import { getNeedLoginPages, getNeedMemberPages, geRoutePages } from '@/utils/pages'

const loginBack = useLogin()

/**
 * 检测是否需要登录
 */
export function checkNeedLogin(route: AnyObject) {
    const pages = getNeedLoginPages()
    if (pages.includes(route.path) && !getToken()) {
        console.log('跳转登录')

        setTimeout(() => {
            loginBack.setLoginBack({ url: route.path, param: route.query || {} })
        }, 100)
    }
}
/**
 * 检测是否需要选择会员
 */
export function checkNeedMember(route: AnyObject) {
    const pages = getNeedMemberPages()

    if (pages.includes(route.path) && !getMember()) {
        setTimeout(() => {
            loginBack.setMemberBack({ url: route.path, param: route.query || {} })
        }, 100)
    }
}
/**
 * 检测是否需要权限
 */
export function checkNeedPermi(route: AnyObject) {
    const pages = geRoutePages(route)
    if (!checkPermi(pages.meta.permission)) {
        let parameter = {
            url: '',
            title: '暂无权限'
        };
        goback(parameter)
    }
    // if (pages.includes(route.path) && !getMember()) {
    //     setTimeout(() => {
    //         loginBack.setMemberBack({ url: route.path, param: route.query || {} })
    //     }, 100)
    // }
}
/**
 * 字符权限校验
 * @param {Array} value 校验值
 * @returns {Boolean}
 */
export function checkPermi(value: string[]) {
    if (value && value instanceof Array && value.length > 0) {
        const permissionDatas = value
        const all_permission = '*:*:*'
        const permissions = uni.getStorageSync('wap_member_permission') || []
        const hasPermission = permissions.some((permission: any) => {
            return all_permission === permission || permissionDatas.includes(permission)
        })
        return !!hasPermission
    } else {
        return false
    }
}